import math
def quadratic(a,b,c):
    if b**2-4*a*c<0:
        print('方程无根')
    if a==0:
        return -b/c
    else:
        x1=(-b+math.sqrt(b*b-a*c*4))/(2*a)
        x2=(-b-math.sqrt(b*b-a*c*4))/(2*a)
    return x1,x2

# 测试:
print('quadratic(2, 3, 1) =', quadratic(2, 3, 1))
print('quadratic(1, 3, -4) =', quadratic(1, 3, -4))

if quadratic(2, 3, 1) != (-0.5, -1.0):
    print('测试失败')
elif quadratic(1, 3, -4) != (1.0, -4.0):
    print('测试失败')
else:
    print('测试成功')




def mul(*n):
    if n==():
        raise TypeError
    
    s=1
    for x in n:
        s=s*x
    return s
# 测试
print('mul(5) =', mul(5))
print('mul(5, 6) =', mul(5, 6))
print('mul(5, 6, 7) =', mul(5, 6, 7))
print('mul(5, 6, 7, 9) =', mul(5, 6, 7, 9))
if mul(5) != 5:
    print('mul(5)测试失败!')
elif mul(5, 6) != 30:
    print('mul(5, 6)测试失败!')
elif mul(5, 6, 7) != 210:
    print('mul(5, 6, 7)测试失败!')
elif mul(5, 6, 7, 9) != 1890:
    print('mul(5, 6, 7, 9)测试失败!')
else:
    try:
        mul()
        print('mul()测试失败!')
    except TypeError:
        print('测试成功!')


        
def move(n,a,b,c):
    if n==1:
        print(a,'-->',c)
    else:
        move(n-1,a,c,b)
        move(1,a,b,c)
        move(n-1,b,a,c)


def findMinAndMax(L):
    if L:
        L_min=L_max=L[0]
        for i in L:
            if i>L_max:
                L_max=i
            if i<L_min:
                L_min=i
        return (L_min,L_max)
    else:
        return (None,None)


# 测试
if findMinAndMax([]) != (None, None):
    print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
    print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
    print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
    print('测试失败!')
else:
    print('测试成功!')


    
def trim(s):
    while s and s[0]==' ':
            s=s[1:]
    while s and s[-1:]==' ':
            s=s[:-1]
    return s

# 测试:
if trim('hello  ') != 'hello':
    print('测试失败!')
elif trim('  hello') != 'hello':
    print('测试失败!')
elif trim('  hello  ') != 'hello':
    print('测试失败!')
elif trim('  hello  world  ') != 'hello  world':
    print('测试失败!')
elif trim('') != '':
    print('测试失败!')
elif trim('    ') != '':
    print('测试失败!')
else:
    print('测试成功!')

def triangles():
   L=[1]
   while True:
       yield L
       L=[1]+[L[i]+L[i+1]for i in range(len(L)-1)]+[1]

# 期待输出:
# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
# [1, 5, 10, 10, 5, 1]
# [1, 6, 15, 20, 15, 6, 1]
# [1, 7, 21, 35, 35, 21, 7, 1]
# [1, 8, 28, 56, 70, 56, 28, 8, 1]
# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
n = 0
results = []
for t in triangles():
    results.append(t)
    n = n + 1
    if n == 10:
        break

for t in results:
    print(t)

if results == [
    [1],
    [1, 1],
    [1, 2, 1],
    [1, 3, 3, 1],
    [1, 4, 6, 4, 1],
    [1, 5, 10, 10, 5, 1],
    [1, 6, 15, 20, 15, 6, 1],
    [1, 7, 21, 35, 35, 21, 7, 1],
    [1, 8, 28, 56, 70, 56, 28, 8, 1],
    [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
]:
    print('测试通过!')
else:
    print('测试失败!')

def normalize(name):
    new_name=name[0].upper()+name[1:].lower()
    return new_name
# 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)


from functools import reduce
def prod(l):
    def mul(x,y):
        return x*y
    return reduce(mul,l)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('测试成功!')
else:
    print('测试失败!')

from functools import reduce
def DIG(s):
    DIGITS={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
    return DIGITS[s]
def mul(x,y):
    return x*10+y
def str2float(s):
    for i in s:
        i=s.find('.')
        s1=s[:i]
        s2=s[i+1:]
    return reduce(mul,map(DIG,s1))+reduce(mul,map(DIG,s2))/10**len(s2)
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')

from functools import reduce
def DIG(s):
    DIGITS={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
    return DIGITS[s]
def mul(x,y):
    return x*10+y
def str2float(s):
   s1=s.split('.')[0]
   s2=s.split('.')[1]
   return reduce(mul,map(DIG,s1))+reduce(mul,map(DIG,s2))/10**len(s2)
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')

def _odd_iter():
    n=1
    while True:
        n=n+2
        yield n
def _not_divisible(n):
    return lambda x:x%n>0
def primes():
    yield 2
    it=_odd_iter()
    while True:
        n=next(it)
        yield n
        it=filter(_not_divisible(n),it)
for n in primes():
    if n<1000:
        print(n)
    else:
        break

def is_palindrome(n):
    return str(n)==str(n)[::-1]
# 测试:
output = filter(is_palindrome, range(1, 1000))
print('1~1000:', list(output))
if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:
    print('测试成功!')
else:
    print('测试失败!')
    
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
   return t[0]
def by_score(t):
    return -t[1]
L1 = sorted(L, key=by_name)
L2 = sorted(L, key=by_score)
print(L1,L2)

def count():
    fs = []
    for i in range(1, 4):
        def f():
             return i*i
    fs.append(f)
    return fs

def count():
    def f(j):
        def g():
            return j*j
        return g
    fs = []
    for i in range(1, 4):
        fs.append(f(i)) # f(i)立刻被执行，因此i的当前值被传入f()
    return fs

def createCounter():
    s=0
    def counter():
        nonlocal s
        s=s+1
        return s
    return counter
# 测试:
counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
    print('测试通过!')
else:
    print('测试失败!')

L=list(filter(lambda n:n%2==1,range(1,20)))
print(L)

import functools

def log(func):
    @functools.wraps(func)
    def wrapper(*args,**kw):
        print('call %s():'% func.__name__)
        return func(*args,**kw)
    return wrapper
@log
def now():
    print('2024-6-1')

import functools

def log(text):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args,**kw):
            print('%s %s():'%(text,func.__name__))
            return func(*args,**kw)
        return wrapper
    return decorator
@log('execute')
def now():
    print('2024-9-12')

def log(func):
    def wrapper(*args,**kw):
        print('call%s():'%func.__name__)
        return func(*args,**kw)
    return wrapper
@log
def now():
    print('2024-6-1')
now()

def log(text):
    def decorator(func):
        def wrapper(*args,**kw):
            print('%s %s() at:'%(text,func.__name__))
            return func(*args,**kw)
        return wrapper
    return decorator
@log('execute')
def now():
    print('2024-6-1')

import functools
def log(func):
    @functools.wraps(func)
    def wrapper(*args,**kw):
        print('call %s():'%func.__name__)
        return func(*args,**kw)
    return wrapper
import functools
def log(text):
    def decorator(func):
        @functool.wraps(func)
        def wrapper(*args,**kw):
            print('%s %s():'%(text,func.__name__))
            return func(*args,**kw)
        return wrapper
    return decorator

import functools
def log(text='execute'):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args,**kw):
            print('%s %s():'%(text,func.__name__))
            return func(*args,**kw)
        return wrapper
    return decorator
import functools  
  
def log(message='default message'):  
    """  
    一个灵活的log装饰器工厂，它返回一个装饰器。  
      
    这个装饰器会在被装饰的函数执行前后打印日志。  
    如果提供了message参数，则使用它；否则，使用默认消息。  
    """  
    def decorator(func):  
        @functools.wraps(func)  
        def wrapper(*args, **kwargs):  
            print(f"Entering {func.__name__} with message: {message}")  
            result = func(*args, **kwargs)  
            print(f"Exiting {func.__name__}")  
            return result  
        return wrapper  
    return decorator  
@log
def now():
    print('2024-6-1')
